<template>
    <div class="home-container">
      <SideMenu />
      <!-- 主内容区 -->
      <div class="main-content"
         @touchstart="handleTouchStart"
         @touchmove="handleTouchMove"
         @touchend="handleTouchEnd">
        <!-- 顶部导航栏 -->
        <!-- <div class="header">
          <UserMenu />
        </div> -->
        <div class="nav-bar">
          <h1 class="page-title">资源管理</h1>
          <div class="nav-items">
            <div v-for="(item, index) in navItems" 
                 :key="index" 
                 :class="['nav-item', { active: currentNav === item }]"
                 @click="currentNav = item">
              {{ item }}
            </div>
          </div>

          <!-- 修改上传按钮的包装样式 -->
          <div class="upload-wrapper">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              :auto-upload="true"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :limit="1"
              :http-request="customUpload"
            >
              <el-tooltip content="上传" placement="top">
                <el-button class="upload-btn" plain>
                  <img src="@/assets/icon/more-icon.png" class="upload-icon" alt="上传" />
                </el-button>
              </el-tooltip>
            </el-upload>
          </div>
        </div>
    
        <!-- 瀑布流内容区 -->
        <div class="content-grid">
          <div v-for="(item, index) in currentPageResources" 
               :key="index" 
               class="grid-item">
            <el-tooltip
              placement="top"
              :content="getFileInfo(item)"
              :show-after="200"
              :hide-after="200"
              effect="dark"
              raw-content>
              <div class="grid-item-content" @click="handleItemClick(item)">
                <div class="file-icon">
                  <!-- 根据文件类型显示不同图标 -->
                  <img :src="getFileIcon(item.filename)" alt="文件" class="file-type-icon">
                </div>
                <div class="item-name">
                  {{ item.filename }}
                </div>
                <!-- 添加操作按钮区域 -->
                <div class="action-buttons" v-if="canOperator(item)">
                  <img 
                    src="@/assets/icon/delete.png" 
                    class="delete-icon" 
                    @click.stop="handleDelete(item)"
                    title="删除"
                  >
                </div>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
  </template>
  
<script setup lang="ts">
  import { ref, onMounted,computed,watch } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { useUserStore } from '@/store/user'
  import { ListResources, DeleteResource,GetResourceUrl, CreateResource } from '@/api/resource'
  import {ListResourcesRequest, ListResourcesResponse, Resource, CreateResourceRequest} from '@/types/proto/api/v1/resource_service'
  import SideMenu from '@/components/SideMenu.vue'
  import UserMenu from '@/components/UserMenu.vue'
  import qipuIcon from '@/assets/icon/qipu-avatar.png'
  import pdfIcon from '@/assets/icon/files/pdf.png'
  import pptIcon from '@/assets/icon/files/ppt.png'
  import docIcon from '@/assets/icon/files/doc.png'
  import excelIcon from '@/assets/icon/files/excel.png'
  import imageIcon from '@/assets/icon/files/image.png'
  import txtIcon from '@/assets/icon/files/txt.png'
  import videoIcon from '@/assets/icon/files/video.png'
  import documentIcon from '@/assets/icon/files/document.png'
  import { formatFileSize, formatDate } from '@/utils/resource'
  import { MAX_FILE_SIZE } from '@/config'
  const router = useRouter()
  const userStore = useUserStore()
  const uploadRef = ref()
  
  const navItems =[""]
  const currentNav = ref('')
  const isAdmin = computed(() => userStore.userInfo?.role === 'TENANT_ADMIN')
  const canOperator = (item: Resource) =>{
    if(isAdmin.value){
      return true
    }
  }


  // const subjects = ref<SubjectItem[]>([])
  const resources = ref<Resource[]>([])
  const totalPages = computed(() => Math.ceil(resourcesTotal.value / pageSize))

  const pageSize = 20 // 每页显示5个
  const currentPage = ref(1)
  const resourcesTotal = ref(0)
  const currentPageResources = computed(() => {
    return resources.value
  })
  // 处理发现点击
  const handleDiscover = () => {
    const pageToken = { limit: pageSize, offset: 0 }
    const filter = ""
    ListResources({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListResourcesResponse)=>{
      resourcesTotal.value = res.resources.length
      resources.value=res.resources 
    }).catch(error => {
        console.error('Failed to fetch news:', error)
    })
  }
  
  const touchStartY = ref(0)
  const touchThreshold = 50  // 触发翻页的阈值

  const beforeUpload = (file: File) => {
    if (file.size > MAX_FILE_SIZE) {
      ElMessage.error('文件大小不能超过100MB')
      return false
    }
    return true
  }

  const handleUploadSuccess = () => {
    ElMessage.success('文件上传成功')
    // Reset the upload component
    uploadRef.value?.clearFiles()
  }

  const handleUploadError = (error: any) => {
    console.error('Error uploading file:', error)
    ElMessage.error('文件上传失败')
  }

  const customUpload = async (options: any) => {
    try {
      const file = options.file
      const fileContent = new Uint8Array(await file.arrayBuffer())
      console.log("doc custom upload file", file)
      let req = {
        filename: file.name, 
        type: file.type,
        content: fileContent
      } as CreateResourceRequest
      console.log("doc custom upload req", req)
      
      let res = await CreateResource(req)
      console.log("doc custom upload res", res)
      console.log("doc handle upload success", res)
      if (res == null) {
        return
      } 
      resources.value.push(res)
      options.onSuccess()
    } catch (error) {
      console.error('Error uploading file:', error)
      options.onError(error)
    }
  }
  // 处理触摸开始
  const handleTouchStart = (event: TouchEvent) => {
    touchStartY.value = event.touches[0].clientY
  }

  // 处理触摸移动
  const handleTouchMove = (event: TouchEvent) => {
    event.preventDefault() // 防止页面滚动
  }

  const getFileInfo = (item: Resource) => {
    const u = item.creator?.nickname || item.creator?.username || '未知用户';
    const fileSize = formatFileSize(item.size);
    const fileDate = formatDate(item.createTime);
    const fileName = item.filename
    const fileType = item.type
    return `文件名：${fileName}<br>文件类型：${fileType}<br>文件大小：${fileSize}<br>上传者： ${u}<br>上传时间：${fileDate}`
  }

  // 处理触摸结束
  const handleTouchEnd = (event: TouchEvent) => {
  const touchEndY = event.changedTouches[0].clientY
  const deltaY = touchEndY - touchStartY.value
  console.log('touch delay:', deltaY, "currenct page:", currentPage.value)

  // 向上滑动，显示下一页
  if (deltaY < -touchThreshold && currentPage.value < totalPages.value) {
    console.log('向上滑动')
    handlePageChange(currentPage.value + 1)
  }
  // 向下滑动，显示上一页
  else if (deltaY > touchThreshold && currentPage.value > 1) {
    console.log('向下滑动')
    handlePageChange(currentPage.value - 1)
  }
}

const showPageHint = () => {
  ElMessage({
    message: currentPage.value === totalPages.value ? '已经是最后一页' : '已经是第一页',
    type: 'info',
    duration: 1500
  })
}


const handlePageChange = (page: number) => {

    if (page < 1 || page > totalPages.value) {
      showPageHint()
      return
    }

    console.log("click page:", page)
    currentPage.value = page

    const pageToken = { limit: pageSize, offset: (page - 1) * pageSize }
    HandleVisibilityPageChange(pageToken)
  }

const HandleVisibilityPageChange = (pageToken: any) => {    // const pageToken = { limit: pageSize, offset: (page - 1) * pageSize }
    const filter = ""
    ListResources({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListResourcesResponse)=>{
      resourcesTotal.value = res.resources.length
      resources.value=res.resources 
    }).catch(error => {
        console.error('Failed to fetch news:', error)
    })
  }
  
  // Add onMounted hook to check token
  onMounted(() => {
    if (!userStore.token) {
      router.push('/signin')
    }
    handleDiscover()
  })

  // 处理项目点击
  const handleItemClick = (item: Resource) => {
    const url = GetResourceUrl(item)
    window.open(url, '_blank')
  }

  const handleMoreClick = (event: Event) => {
    event.stopPropagation()
  }

  const showFileName = (filename: string) => {
    console.log("filename:", filename)
    console.log("filename.length:", filename.length)
    if(filename.length > 15){
      let f = filename.slice(0, 15) 
      console.log("f:", f)
      return f + '...'
    } else {
      return filename
    }
  }
  // 根据文件名获取文件图标
  const getFileIcon = (filename: string) => {
    const extension = filename.split('.').pop()?.toLowerCase()
    
    if (!extension) return documentIcon
    
    switch (extension) {
      case 'pdf':
        return pdfIcon
      case 'pptx':
      case 'ppt':
      case 'pptm':
        return pptIcon
      case 'docx':
      case 'doc':
        return docIcon
      case 'xlsx':
      case 'xls':
        return excelIcon
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return imageIcon
      case 'txt':
        return txtIcon
      case 'mp4':
      case 'avi':
      case 'mov':
        return videoIcon
      default:
        return documentIcon
    }
  }

  const handleEdit = (item: Resource) => {
    router.push(`/resource/config?resource=${item.urn}`)
  }

  const handleDelete = (item: Resource) => {
    DeleteResource({urn:item.urn}).then(() => {
      resources.value = resources.value.filter(a => a.urn !== item.urn)
      ElMessage.success('删除成功')
      // 可以在这里刷新列表
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  }
  </script>
  
  <style scoped lang="scss">
  .home-container {
    display: flex;
    max-width: 1440px;
    margin: 0 auto;
    padding: 0;
  }
  
  .main-content {
    flex: 1;
    margin-left: 100px;
    padding: 20px 40px;
  }
  
  .header {
    display: flex;
    justify-content: flex-end;
    padding: 8px 16px;
    border-bottom: 1px solid #eee;
  }
  
  .nav-bar {
    position: sticky;
    top: 0;
    background: white;
    padding: 10px 0;
    z-index: 100;
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  
    .create-button {
      cursor: pointer;
      padding: 8px;
      border-radius: 4px;
      transition: background-color 0.2s;
  
      &:hover {
        background-color: #f5f5f5;
      }
  
      .create-icon {
        width: 24px;
        height: 24px;
      }
    }
  
    .nav-items {
      display: flex;
      gap: 24px;
      overflow-x: auto;
      padding: 0;
  
      .nav-item {
        cursor: pointer;
        white-space: nowrap;
        color: #666;
        
        &.active {
          color: #333;
          font-weight: bold;
        }
  
        &:hover {
          color: #333;
        }
      }
    }

    // 添加上传按钮包装器样式
    .upload-wrapper {
      display: flex;
      align-items: center;
    }

    .upload-demo {
      display: inline-block;
    }

    .upload-btn {
      padding: 8px;
      border: none;
      background: rgba(0, 0, 0, 0.04);
      height: auto;
      
      &:hover {
        background: rgba(0, 0, 0, 0.08);
      }
    }

    .upload-icon {
      width: 20px;
      height: 20px;
      vertical-align: middle;
    }
  }
  .content-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 24px;
    padding: 16px 0;
    justify-items: center;
  }
  
  .grid-item {
    width: 100%;
    max-width: 200px;  // 调整最大宽度
    height: 200px;     // 固定高度
    border-radius: 8px;
    overflow: hidden;
    background: white;
    transition: all 0.2s;
    cursor: pointer;
    position: relative;  // 添加相对定位
    padding-bottom: 32px;  // 为底部用户信息留出空间
  
    &:hover {
      transform: translateY(-2px);
    }

    .grid-item-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;
      padding: 15px;
    }
    
    .file-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 20px 0;
      
      .file-type-icon {
        width: 72px;
        height: 72px;
        object-fit: contain;
      }
    }
    
    .item-name {
      font-size: 14px;
      font-weight: 500;
      color: #333;
      text-align: center;
      margin-bottom: 1px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      width: 100%;
    }
  
    .item-info {
      position: absolute;  // 绝对定位
      bottom: 0;          // 固定在底部
      left: 0;           // 左对齐
      width: 100%;       // 占满宽度
      padding: 8px;
      background: white; // 确保背景是白色
      border-top: 1px solid #f0f0f0;
  
      h3 {
        margin: 0 0 4px;
        font-size: 13px;
        line-height: 1.3;
        display: -webkit-box;
        -webkit-line-clamp: 5;
        line-clamp: 5; 
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
  
      .user-info {
        display: flex;
        align-items: center;
        gap: 4px;
        
        span {
          font-size: 11px;
          color: #666;
        }

        .el-avatar {
          width: 20px;
          height: 20px;
        }
      }
  
      .matter-title {
        font-size: 13px;
        margin: 4px 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align: left;
        padding: 0 8px;
      }
  
      .interaction {
        font-size: 11px;
        color: #999;
  
        i {
          margin-right: 3px;
        }
      }
    }

    .prompt-text {
      padding: 8px;
      font-size: 12px;
      color: #666;
      display: -webkit-box;
      -webkit-line-clamp: 5;  // 最多显示5行
      line-clamp: 5;          // 标准属性
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      line-height: 1.4;
      text-align: left;
    }

    .action-buttons {
      right: 8px;
      bottom: 8px;
      opacity: 0;
      transition: opacity 0.2s;
      z-index: 2;

      .delete-icon {
        width: 16px;
        height: 16px;
        cursor: pointer;
        transition: transform 0.2s;

        &:hover {
          transform: scale(1.1);
        }
      }
    }

    &:hover {
      .action-buttons {
        opacity: 1;
      }
    }
  }
  
  .action-menu {
    .action-item {
      display: flex;
      align-items: center;
      padding: 8px;
      cursor: pointer;
      
      &:hover {
        background-color: #f5f5f5;
      }

      .action-icon {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }

      span {
        font-size: 12px;
        color: #333;
      }
    }
  }
  
  @media screen and (max-width: 1440px) {
    .home-container {
      max-width: 100%;
    }
    
    .main-content {
      margin-left: 220px;
    }
    
    .content-grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      gap: 20px;
    }
    .grid-item {
      max-width: 160px;
      height: 180px;
    }
  }
  
  @media screen and (max-width: 1200px) {
    .main-content {
      margin-left: 200px;
    }
    
    .content-grid {
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 16px;
    }
    .grid-item {
      max-width: 140px;
      height: 160px;
    }
  }
  </style>